﻿using Abp.Timing;
using DotNetCore.CAP;
using Hicap.QRCodeWarehouse.Processor.Const;
using Hicap.QRCodeWarehouse.Processor.Manager;
using Hicap.QRCodeWarehouse.Processor.Model;
using Serilog;
using System;
using System.Diagnostics;
using System.Threading.Tasks;

namespace Hicap.QRCodeWarehouse.Processor.Service
{
    /// <summary>
    /// Warehouse Global Monitor
    /// </summary>
    public class MonitorService : ServiceBase, IMonitorService, ICapSubscribe
    {
        private readonly IMonitorManager _monitorManager;
        private readonly ICapPublisher _capBus;

        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="monitorManager">IMonitorManager</param>
        /// <param name="capBus">ICapPublisher</param>
        public MonitorService(IMonitorManager monitorManager, ICapPublisher capBus)
        {
            //kenrel manager
            _monitorManager = monitorManager;

            //Cap send bus
            _capBus = capBus;
        }

        /// <summary>
        /// response monitor command action
        /// </summary>
        [CapSubscribe(MessageQueueChanelConst.MonitorServiceAction, Group = SysConst.SysName)]
        public async Task<ActionResult> DispatcherMonitorAction(int type)
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();
            try
            {
                //get infos
                MonitorFeedback[] infos = await _monitorManager.GetMonitorInfos(type);

                //send infos
                await _capBus.PublishAsync(MessageQueueChanelConst.MonitorServiceFeedBack, infos,
                    MessageQueueChanelConst.MonitorServiceFeedBack + ".End");

                Log.Information($"Warhouse Monitor Infos:{infos}");

                return new ActionResult(MessageQueueChanelConst.MonitorServiceAction, true, watch.ElapsedMilliseconds,
                    Clock.Now, type);
            }
            catch (Exception e)
            {
                return new ActionResult(MessageQueueChanelConst.MonitorServiceAction, false, watch.ElapsedMilliseconds,
                    Clock.Now, type, e);
            }
        }

        [CapSubscribe(MessageQueueChanelConst.MonitorServiceFeedBack + ".End", Group = SysConst.SysName)]
        public void FinalFeedBackMessage(ActionResult result)
        {
            if (result.IsSuccessed)
                Log.Information($"FeedBack Finished:{MessageQueueChanelConst.MonitorServiceFeedBack}--{result}");
            else
                Log.Error($"FeedBack have a Error:{MessageQueueChanelConst.MonitorServiceFeedBack}--{result}");
        }
    }
}